package com.genesis.yunnanji.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.genesis.yunnanji.R;
import com.genesis.yunnanji.config.GenesisApiConfig;
import com.jaeger.library.StatusBarUtil;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;


public class WebActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, View.OnClickListener {
    private WebView mWebView;
    private ProgressBar mProgressBar;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private Toolbar mToolbar;
    private String url;
    private String id;
    private RelativeLayout share;

    public static final int MIN_CLICK_DELAY_TIME = 1000;
    private long lastClickTime = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.activity_webactivity);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        share = (RelativeLayout) findViewById(R.id.bt_web_share);
        mWebView = (WebView) findViewById(R.id.wv_web_webview);
        mProgressBar = (ProgressBar) findViewById(R.id.pb_web_progress);
        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.sr_web_swipe);
        mSwipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.main_color));
        mToolbar = (Toolbar) findViewById(R.id.tb_web_toolbar);
        mToolbar.setBackgroundColor(getResources().getColor(R.color.main_color));
        mToolbar.setTitle("");
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mWebView.canGoBack()) {
                    mWebView.goBack();
                } else {
                    finish();
                }
            }
        });
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        StatusBarUtil.setColor(this, getResources().getColor(R.color.main_color), 2);
        url = getIntent().getStringExtra("url");
        id = getIntent().getStringExtra("news_id");
        if (getIntent().getStringExtra("title") != null) {
            mToolbar.setTitle(getIntent().getStringExtra("title"));
        }

    }

    @Override
    protected void setUpView() {
        Log.e("url", url);
        share.setOnClickListener(this);
        mWebView.loadUrl(url);
        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setEnabled(false);
        mProgressBar.setMax(100);
        setUpWebview();
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mWebView.canGoBack()) {
                    mWebView.goBack();
                } else {
                    finish();
                }
            }
        });
    }

    private void setUpWebview() {
        mWebView.setWebChromeClient(new MyWebChromeClient());
        mWebView.setWebViewClient(new mWebClient());
        mWebView.getSettings().setUseWideViewPort(true);
        mWebView.getSettings().setAllowFileAccess(true);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setAppCacheEnabled(false);
        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings().setBuiltInZoomControls(false);
        mWebView.getSettings().setDefaultFontSize(12);
        mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.getSettings().setAllowFileAccess(true);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebView.getSettings().setDatabaseEnabled(true);
        mWebView.getSettings().setGeolocationEnabled(true);
        mWebView.getSettings().setPluginState(WebSettings.PluginState.ON);
        if (Build.VERSION.SDK_INT >= 21) {
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        mWebView.addJavascriptInterface(new JsInterface(), "callapp");
    }

    @Override
    public void onRefresh() {
        mWebView.loadUrl(mWebView.getUrl());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_web_share:
                UMImage thumb = new UMImage(context, R.mipmap.sharelog);
                String[] str = mWebView.getUrl().split("__apptoken__");
                String shareUrl = str[0];
                UMWeb web = new UMWeb(shareUrl);
                web.setTitle(mWebView.getTitle());//标题
                web.setThumb(thumb);
                web.setDescription(mWebView.getTitle());
                new ShareAction(WebActivity.this)
                        .withMedia(web)
                        .setDisplayList(SHARE_MEDIA.QQ, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.QZONE, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.SMS, SHARE_MEDIA.WEIXIN_FAVORITE, SHARE_MEDIA.EMAIL)
                        .open();
                break;
        }
    }

    String webTitle;

    private class MyWebChromeClient extends WebChromeClient {


        @Override
        public void onReceivedTitle(WebView view, String title) {
            // TODO Auto-generated method stub
            mToolbar.setTitle(title);
            webTitle = title;

        }


        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                mProgressBar.setVisibility(View.GONE);
                mSwipeRefreshLayout.setRefreshing(false);

            } else {
                if (mProgressBar.getVisibility() == View.GONE) {
                    mProgressBar.setVisibility(View.VISIBLE);
                    mProgressBar.setProgress(newProgress);
                }
                if (!mSwipeRefreshLayout.isRefreshing()) {
                    mSwipeRefreshLayout.setRefreshing(true);
                }
            }
            super.onProgressChanged(view, newProgress);
        }
    }

    private class mWebClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith("tel:")) {
                Intent intent = new Intent(Intent.ACTION_VIEW,
                        Uri.parse(url));
                startActivity(intent);
                return true;
            } else {
                if (Build.VERSION.SDK_INT < 26) {
                    view.loadUrl(url);
                    return true;
                }

            }
            return false;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            share.setVisibility(View.VISIBLE);
            super.onPageFinished(view, url);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        } else {
            finish();
        }
        return false;
    }

    private void settext() {
        String title = "";
        mWebView.getId();
    }


    @Override
    public void onPause() {
        super.onPause();
        mWebView.onPause();
        mWebView.pauseTimers();
    }

    @Override
    public void onResume() {
        super.onResume();
        mWebView.resumeTimers();
        mWebView.onResume();
    }

    @Override
    protected void onDestroy() {
        mWebView.destroy();
        mWebView = null;
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @SuppressLint("JavascriptInterface")
    final class JsInterface {
        public JsInterface() {
        }

        @JavascriptInterface
        public void Pay(String id) {

            Intent intent = new Intent(context, SelectPay.class);
            intent.putExtra("id", id);
            startActivity(intent);
        }

        @JavascriptInterface
        public void Login() {
            Intent intent = new Intent(context, Login.class);
            startActivity(intent);
        }

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getEvent(String num) {
        Log.e("event", num);
        if (num.equals("login")) {
            mWebView.loadUrl(mWebView.getUrl() + GenesisApiConfig.APP_TOKEN + genesisUtils.getAppToken());
        } else {
            mWebView.loadUrl(GenesisApiConfig.HOST + "/Mall/Center/orders.html");
        }
    }


}
